/*
 * @Author: yanjikun
 * @Date: 2022-04-13 10:48:30
 * @LastEditors: yanjikun
 * @LastEditTime: 2022-04-13 11:35:56
 * @Description: file content
 */

import { isFunction } from '@/utils/is'
import { tryOnUnmounted } from '@vueuse/core'
import { ref, watch } from 'vue'

export type TimeoutRef = ReturnType<typeof useTimeoutRef>
/**
 * @description: setTimeout二次封装
 * @param {Fn} handle 需要延时执行的函数
 * @param {number} wait 延时的时间(毫秒)
 * @param {boolean} native 是否立即执行
 * @return {TimeoutRef}
 * @author: yanjikun
 */
export const useTimeoutFn = (
  handle: Fn<any>,
  wait: number,
  native: boolean = false
): TimeoutRef => {
  if (!isFunction(handle)) {
    throw new Error('handle 不是函数！请检查')
  }
  const { readyRef, start, stop } = useTimeoutRef(wait)
  if (native) {
    handle()
  } else {
    watch(
      readyRef,
      (maturity) => {
        maturity && handle()
      },
      { immediate: false }
    )
  }
  return {
    readyRef,
    stop,
    start
  }
}

/**
 * @description: setTimeout 停止和开始方法
 * @param {number} wait 延时执行的时间
 * @return {*}
 * @author: yanjikun
 */
export const useTimeoutRef = (wait: number) => {
  const readyRef = ref(false)
  let timer: TimeoutHandle
  const stop = (): void => {
    readyRef.value = false
    timer && window.clearTimeout(timer)
  }
  const start = (): void => {
    stop()
    timer = setTimeout(() => {
      readyRef.value = true
    }, wait)
  }
  start()
  tryOnUnmounted(stop)
  return { readyRef, start, stop }
}
